import React, { useEffect, useState } from "react";
import { useNavigate, NavLink } from "react-router-dom";
import { Dropdown, Space, Avatar, message } from "antd";
import { UserOutlined } from "@ant-design/icons";
import { useStore } from "../stores/store.jsx"; // 引入全局状态
import Cookies from "js-cookie";
import { USER_TYPES } from "../utils/userUtils"; // 用户类型常量

import "../assets/style/topnav.css"; // 样式文件

const TopNav = () => {
  const { state, dispatch } = useStore(); // 获取全局状态
  const navigate = useNavigate(); // 路由跳转
  const [avatarUrl, setAvatarUrl] = useState("");
  const isLoggedIn = !!Cookies.get("access_token"); // 检测是否已登录
  const username = state.userInfo?.real_name || "用户"; // 获取用户名
  const userType = state.userType; // 获取用户类型
  useEffect(() => {
    if (state.userInfo?.avatar) {
      // 添加时间戳防止缓存
      const timestamp = new Date().getTime();
      setAvatarUrl(
        `${import.meta.env.VITE_APP_MEDIA_URL}/${
          state.userInfo.avatar
        }?t=${timestamp}`
      );
    }
  }, [state.userInfo]);
  // 退出登录方法
  const handleLogout = () => {
    dispatch({ type: "CLEAR_USER_INFO" });
    Cookies.remove("access_token");
    localStorage.removeItem("user"); // 双重保障
    message.success("已退出登录");
    navigate("/home");

    // 强制刷新页面确保状态归零
    setTimeout(() => window.location.reload(), 500);
  };

  // 检查登录状态并跳转
  const handleNavClick = (e, path) => {
    if (!isLoggedIn) {
      e.preventDefault(); // 阻止默认跳转行为
      message.warning("请先登录！");
      navigate("/login"); // 跳转到登录页面
    } else {
      navigate(path); // 已登录则跳转到目标页面
    }
  };

  // 根据用户类型动态生成导航栏标签
  let tabs = [];
  if (userType === USER_TYPES.RECRUITER) {
    tabs = [
      { label: "首页", path: "/home" },
      { label: "发布职位", path: "/home/post-job" },
      { label: "候选人管理", path: "/home/candidates" },
      { label: "面试安排", path: "/home/interviews" },
    ];
  } else if (userType === USER_TYPES.JOB_SEEKER) {
    tabs = [
      { label: "首页", path: "/home" },
      { label: "职位", path: "/home/jobs" },
      { label: "校园", path: "/home/campus" },
      { label: "海归", path: "/home/overseas" },
      { label: "来财APP", path: "/home/app" },
    ];
  }

  return (
    <header className="navbar">
      <div className="navbar-logo">
        <img src="/images/logo.png" alt="来财" className="logo" />
      </div>
      <nav className="navbar-links">
        {tabs.map((tab) => (
          <NavLink
            key={tab.path}
            to={tab.path}
            className={({ isActive }) => (isActive ? "active-link" : "")}
            onClick={(e) => handleNavClick(e, tab.path)}
          >
            {tab.label}
          </NavLink>
        ))}
      </nav>
      <div className="navbar-user">
        {isLoggedIn ? (
          <Dropdown
            menu={{
              items: [
                {
                  key: "settings",
                  label: <span onClick={() => navigate("")}>设置</span>,
                },
                {
                  key: "resume",
                  label: <span onClick={() => navigate("")}>我的简历</span>,
                },
                {
                  key: "profile",
                  label: <span onClick={() => navigate("")}>个人信息</span>,
                },
                {
                  key: "logout",
                  label: <span onClick={handleLogout}>退出登录</span>,
                },
              ],
            }}
            trigger={["hover"]}
          >
            <Space>
              <span>你好，{username}</span>
              <Avatar
                src={avatarUrl || null}
                icon={!avatarUrl && <UserOutlined />}
              />
            </Space>
          </Dropdown>
        ) : (
          <Space>
            <span
              className="navbar-link"
              onClick={() => navigate("/login")}
              style={{ cursor: "pointer" }}
            >
              登录
            </span>
          </Space>
        )}
      </div>
    </header>
  );
};

export default TopNav;
